/*
 * 输入验证码
 * page输入验证码
 */
import 'dart:async';
import 'dart:convert';
import 'package:flt_telephony_info/flt_telephony_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:openinstall_flutter_plugin/openinstall_flutter_plugin.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pin_input_text_field/pin_input_text_field.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/api.dart';
import 'package:qgchat/http/models/DeviceInfoModel.dart';
import 'package:qgchat/widgets/newManDialog/NewManDialog.dart';

class InputCode extends StatefulWidget {
  InputCode(this.tel, {Key key}) : super(key: key);

  final String tel;

  @override
  IinputCodeState createState() => IinputCodeState();
}

class IinputCodeState extends State<InputCode> {
  // 获取验证码文字
  String _getCodeText = "获取验证码";
  // 验证码倒计时时间
  int _codeDate = 59;
  // 倒计时控制器
  Timer _codeTimer;
  // 验证码个数
  int codeCount = 4;
  // 验证码控制器
  TextEditingController iptPINController;

  OpeninstallFlutterPlugin _openinstallFlutterPlugin;

  // 邀请码
  String code;

  @override
  void initState() {
    super.initState();

    _openinstallFlutterPlugin = OpeninstallFlutterPlugin();
    _openinstallFlutterPlugin.init((Map<String, dynamic> data) async {});
    _openinstallFlutterPlugin.install((Map<String, dynamic> data) async {
      final bindData = jsonDecode(data['bindData']);
      if (!empty(bindData) && bindData is Map) {
        code = bindData['share'];
      }
    });

    // 提现获取设备信息

    iptPINController = TextEditingController()
      ..addListener(() async {
        String pin = iptPINController.text;
        if (pin.length == 4) {
          var result = await UserApis.PINLogin(widget.tel.replaceAll('"', ''), pin);
          if (result != null && result['status'] == 1) {
            final token = result['msg'];
            final memberToken = result['data']['member_token'];
            final isRegister = result['data']['isRegister'] == 1;

            // 注册
            if (isRegister) {
              // 渠道注册点记录
              apkChannel();
              // openinstall注册埋点
              _openinstallFlutterPlugin.reportRegister();
              // 注册日志
              CommonAction.deviceDetailInfo().then((device) {
                UserApis.registerLog(device.toJson());
              });
              // 绑定邀请关系
              if (!empty(code)) {
                UserApis.isinvitationcode(memberToken).then((bool isset) {
                  if (!isset) UserApis.sharehref(memberToken, code);
                });
              }
            }

            iptPINController.clear();
            CommonAction.initAppData(context, token).then((res) {
              goPage(context, "/", clearStack: true);
            }).catchError(() {
              toast('登录失败');
            });
          }
        }
      });
  }

  @override
  void dispose() {
    _codeTimer?.cancel();
    _codeTimer = null;
    iptPINController.dispose();
    super.dispose();
  }

// methods----------------------------------------------------------------------

  // back
  void _back() {
    Navigator.of(context).pop();
  }

  // 获取验证码方法
  _getCodeAction() {
    if (_codeTimer != null) {
      print(_codeTimer);
      return null;
    }
    _codeTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_codeDate > 0) {
          _getCodeText = '${_codeDate--}秒重新获取';
        } else {
          _getCodeText = '获取验证码';
          _codeDate = 59;
          _codeTimer.cancel();
          _codeTimer = null;
        }
      });
    });
  }

  // 渠道功能
  apkChannel() {
    switch (Config.apkChannel) {
      case ApkChannel.baidu:
        baiduReg();
        break;
      default:
    }
  }

  //百度注册方法
  baiduReg() async {
    PermissionHandler()
        .requestPermissions([PermissionGroup.phone]).then((res) async {
      TelephonyInfo info = await FltTelephonyInfo.info;
      final anid = info.meid;
      CommonApis.baiduRegister(anid);
    });
  }

// widget-----------------------------------------------------------------------

  /// 背景图
  Widget BG() {
    return Container(
      width: w100(context),
      height: h100(context),
      child: Image.asset(
        'assets/images/homeBg1.png',
        fit: BoxFit.cover,
      ),
    );
  }

  /// 返回
  Widget back() {
    return Container(
      margin: EdgeInsets.only(top: px(35)),
      child: GestureDetector(
          onTap: _back,
          child: Container(
            alignment: Alignment.topLeft,
            margin: EdgeInsets.all(px(10)),
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: px(36),
            ),
          )),
    );
  }

  /// 服务协议
  Widget agreement() {
    return Container(
      margin: EdgeInsets.only(top: px(60)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "确认登录即代表已阅读并同意",
            style: TextStyle(
              fontSize: px(22),
              color: col("ffffff"),
            ),
          ),
          FlatButton(
            onPressed: () => {},
            padding: EdgeInsets.zero,
            child: Text(
              "《软件服务协议》",
              style: TextStyle(
                  fontSize: px(22),
                  color: col("ffffff"),
                  fontWeight: FontWeight.bold),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          /// BG
          BG(),

          /// body
          SafeArea(
            child: Container(
              width: w100(context),
              child: ListView(
                children: <Widget>[
                  /// back
                  back(),
                  Container(
                    padding: EdgeInsets.only(
                        bottom: px(50), left: px(60), right: px(60)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(top: px(90)),
                          child: Text(
                            "请输入验证码",
                            style: TextStyle(
                              color: col("ffffff"),
                              fontSize: px(50),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: px(40), bottom: px(50)),
                          child: Text(
                            "验证码已发至手机 ${widget.tel.replaceAll('"', '')}",
                            style: TextStyle(
                              color: col("ede2f6"),
                              fontSize: px(28),
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: px(150)),
                          child: Text(
                            "$codeCount 位数字验证码",
                            style: TextStyle(
                              color: col("ede2f6"),
                              fontSize: px(32),
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: px(50)),
                          child: PinInputTextField(
                            controller: iptPINController,
                            pinLength: codeCount,
                            decoration: UnderlineDecoration(
                              color: col("cd96c8"),
                              enteredColor: col("f4e9f5"),
                            ),
                            // controller: _pinEditingController,
                            autoFocus: false,
                            textInputAction: TextInputAction.go,
                            onSubmit: (pin) {
                              debugPrint('submit pin:$pin');
                            },
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: px(70)),
                          alignment: Alignment.center,
                          child: Text(
                            _getCodeText,
                            style: TextStyle(
                              color: col("d5a7c8"),
                              fontSize: px(28),
                            ),
                          ),
                        ),
                        agreement(),
                      ],
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
